package sadmin

import (
	"errors"
	"github.com/astaxie/beego/orm"
	"github.com/dgrijalva/jwt-go"
	"shop/models/common"
	"strings"
	"time"
)

type User struct {
	Id int
	Username string
	Account string
	Password string
	Company string
	Role string
}

func init()  {
	orm.RegisterModel(new(User))
}

type ResponseType struct {
	Token string
	Username string
	Account string
	Company string
	Role string
}

const superadmin  ="超级管理员"
const admin  ="公司管理员"
const admin1  ="公司副管理员"
const person  ="公司员工"

func Login(account string,password string) (string,error) {
	er:=findAccount(account)
	if er==nil{
		//有账号，继续验证密码
			pwd:=findPassword(account)
			if pwd!=password{
				return "",errors.New("account or password error")
			}
			//r:=findRole(account)
			t,e:=GetToken()
			return t+","+account,e
	}
	return "",errors.New("account or password error")
}

func Logon(u User) (int64,error) {
	if (u.Username==""||u.Account==""||u.Password==""||u.Company==""){
		return 0,errors.New("it can't be null")
	}else {
		str:=common.StrDelTrim(u.Account)
		t:=common.StrCheckChinese(str)
		if (t==false||len(str)<6){
			return 0,errors.New("it can only be numbers or letters and the length is greater than 6")
		}else {
			if findAccount(common.StrDelTrim(u.Account))==nil{
				return 0,errors.New("account is exist")
			}else {
				if _,err:=findByName(u.Company);err!=nil{
					return 0,errors.New("company don't exist")
				}
				o:=orm.NewOrm()
				u.Role=person
				return  o.Insert(&u)
			}

		}
	}
}

//super admin .......
func AdminAdd(account string,u User)(int64,error)  {
		u.Username=common.StrDelTrim(u.Username)
		u.Account=common.StrDelTrim(u.Account)
		u.Password=common.StrDelTrim(u.Password)
		u.Company=common.StrDelTrim(u.Company)
		u.Role=common.StrDelTrim(u.Role)
	if (u.Username==""||u.Account==""||u.Password==""||u.Company==""||u.Role==""){
		return 0,errors.New("it can't be null")
	}else {
		str:=common.StrDelTrim(u.Account)
		 t:=common.StrCheckChinese(str)
		 if (t==false||len(str)<6){
			 return 0,errors.New("it can only be numbers or letters and the length is greater than 6")
		 }else {
		 	if findAccount(common.StrDelTrim(u.Account))==nil{
		 		return 0,errors.New("account is exist")
			}else {
				//根据账号获取角色
				role:=findRole(account)
				//角色判断
				//角色不是1，所属公司不可填写
				if role!=1{
					//当前账号所属公司不变
					u.Company=getCompany(account)
				}
				//角色是2，账号角色可以是3，4
				if role==2{
					if u.Role==superadmin||u.Role==admin{
						return 0,errors.New("have no access")
					}
				}
				//角色是3，账号角色是4
				if role==3{
					if u.Role==superadmin||u.Role==admin||u.Role==admin1{
						return 0,errors.New("have no access")
					}
				}
				if role==4 {
					return 0,errors.New("have no access")
				}

				o:=orm.NewOrm()
				return  o.Insert(&u)
			}

		 }
	}
}

func S(pass string) error {
    var	user User
	user.Username="Super"
	user.Account="super"
	if findAccount(common.StrDelTrim(user.Account))==nil{
		return errors.New("exist")
	}
	user.Password=pass
	user.Role=superadmin
	o:=orm.NewOrm()
	o.Insert(&user)
	return nil
}


func AdminShow(account string,company string,role string)([]User, error)  {
	rol:=findRole(account)
	if rol!=1{
		company=getCompany(account)
	}
	if rol>=changeRole(role){
		return nil,errors.New("have no access")
	}else {
		o := orm.NewOrm()
		var c []User
		com := new(User)
		qs := o.QueryTable(com)
		if common.StrDelTrim(role)!=""{
			qs=qs.Filter("role", role)
		}
		if common.StrDelTrim(company)!=""{
			qs=qs.Filter("company", company)
		}
		_, err := qs.All(&c)
		return c, err
	}
}

func AdminShowById(id int)User  {
	o:=orm.NewOrm()
	com:=User{Id:id}
	_=o.Read(&com,"id")
	return com
}

func AdminEdit(account string,u User) error {
	o := orm.NewOrm()
	user := User{Id: u.Id}
	if o.Read(&user) == nil {
		role:=findRole(account)
		//if u.Username!=""{
		//	user.Username=u.Username
		//}
		ac:=common.StrDelTrim(u.Account)
		u.Username=common.StrDelTrim(u.Username)
		u.Password=common.StrDelTrim(u.Password)
		u.Company=common.StrDelTrim(u.Company)
		u.Role=common.StrDelTrim(u.Role)
		if ac!=""&&u.Username!=""&&u.Password!=""&&u.Company!=""&&u.Role!=""{
			if len(ac)<6&&common.StrCheckChinese(ac)==false{
				return errors.New("account is wrong")
			}else if findAccount(ac)==nil{
				if ac==user.Account{

				}else {
					return errors.New("account is exist")
				}
			}else {
				user.Account=u.Account
			}
			user.Username=u.Username
			user.Password=u.Password
			//角色判断，不是超管就不可更改
			if role!=1{
				//当前公司名称
				c:=getCompany(account)
				user.Company=c
			}else {
				user.Company=u.Company
			}

			//如果当前角色设置的角色超过自己的角色权限，则返回权限不足
			if role<changeRole(u.Role){
				user.Role=u.Role
			}else{
				return errors.New("have no access")
			}
		}else {
			return errors.New("can't be null")
		}
		if _, err := o.Update(&user); err == nil {
			return nil
		}
		return nil
	}else {
		return errors.New("don't exist")
	}
}

func AdminDel(account string,id int)  error{
	if findAccountId(id)!=nil{
		return errors.New("account dont exist")
	}else {
		//权限不足则返回
		role:=findRole(account)
		r:=findRoleById(id)
		if role>=changeRole(r){
			return errors.New("have no access")
		}else {
			o:=orm.NewOrm()
			_,err:=o.Delete(&User{Id:id})
			return err
		}
	}
}

func findAccount(name string) error  {
	o:=orm.NewOrm()
	com:=User{Account:name}
	err:=o.Read(&com,"account")
	return err
}

func FindUserMsg(account string)User  {
	o:=orm.NewOrm()
	com:=User{Account:account}
	o.Read(&com,"account")
	return com
}

func getCompany(account string)string  {
	o:=orm.NewOrm()
	com:=User{Account:account}
	err:=o.Read(&com,"account")
	if err==nil{
		return com.Company
	}
	return ""
}

func findCompany(name string) error  {
	o:=orm.NewOrm()
	com:=User{Company:name}
	err:=o.Read(&com,"company")
	return err
}

func findPassword(account string)string  {
	o:=orm.NewOrm()
	com:=User{Account:account}
	err:=o.Read(&com,"account")
	if err==nil{
		return com.Password
	}
	return ""
}
func findRole(account string)int  {
	o:=orm.NewOrm()
	com:=User{Account:account}
	err:=o.Read(&com,"account")
	if err==nil{
		//将角色进行转换，超管1，公管2，公副管3，员工和其他4

		return changeRole(com.Role)
	}
	return 4
}

func changeRole(role string)int  {
	if role==superadmin{
		return 1
	}else if role==admin{
		return 2
	}else if role==admin1{
		return 3
	}else {
		return 4
	}
}

func findRoleById(id int)string  {
	o:=orm.NewOrm()
	com:=User{Id:id}
	_=o.Read(&com,"id")
	return com.Role
}

func findAccountId(id int)error  {
	o:=orm.NewOrm()
	com:=User{Id:id}
	err:=o.Read(&com,"id")
	return err
}
func GetToken()(string, error)  {
	token:=jwt.New(jwt.SigningMethodHS256)
	claims:=make(jwt.MapClaims)
	claims["exp"]=time.Now().Add(1*time.Hour*time.Duration(1)).Unix()
	claims["iat"]=time.Now().Unix()
	token.Claims=claims

	tokenStr,err:=token.SignedString([]byte("sign"))
	if err!=nil{
		return "",err
	}else {
		return tokenStr,nil
	}
}

func CheckToken(s string)(error)  {
	st:=strings.Split(s," ")
	if len(st)==1{
		return errors.New("token null")
	}else {
		s=st[1]
		token,err:=jwt.Parse(s, func(token *jwt.Token) (i interface{}, e error) {
			return []byte("sign"),nil
		})

		if err!=nil{
			return err
		}else {
			if token.Claims.Valid()!=nil{
				return err
			}else {
				return nil
			}
		}
	}
}